package com.zhouwd.zcamera;


import android.annotation.SuppressLint;
import android.content.Context;

import android.content.res.AssetManager;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;

import android.hardware.Camera;
import android.opengl.GLSurfaceView;

import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;

import android.view.WindowManager;


import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class PreviewRender implements GLSurfaceView.Renderer , Camera.PreviewCallback {

    private static final String TAG = PreviewRender.class.getSimpleName();



    private Context mContext;
    private int mWidth = 1280;

    private int mHeight = 720;

    private SurfaceTexture surfaceTexture;
    private GLSurfaceView mGlSurfaceView;
    //private VideoEncode videoEncode;
    //private MediaRecordManager mediaRecordManager;
    @SuppressLint("MissingPermission")
    public PreviewRender(Context context,GLSurfaceView glSurfaceView) {
        Log.i(TAG, "PreviewRender: ");
        this.mContext = context;
        this.mGlSurfaceView = glSurfaceView;
        //this.mediaRecordManager = mediaRecordManager;
        surfaceTexture = new SurfaceTexture(10);
    }

    private Camera mCamera;

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        try {

            openCamera();

            JniUtil.init(mContext.getAssets());
            String fileName = Environment.getExternalStorageDirectory() + File.separator + "zhouwd" + System.currentTimeMillis() + ".mp4";
            Log.e(TAG, "onSurfaceCreated: fileName --> " + fileName);
            JniUtil.initMediaRecord(fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 打开相机
     */
    public void openCamera() {
        try {

            //获取有多少个摄像头
            mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);

            if (mCamera == null) {
                // Seeing this on Nexus 7 2012 -- I guess it wants a rear-facing camera, but
                // there isn't one.
                //throw new RuntimeException("Default camera not available");
                Log.e(TAG, "openCamere, mCamera == null!");
                return;
            }

            //获取照相机参数
            Camera.Parameters params = mCamera.getParameters();


            //设置预览数据的类型会YV12格式
            params.setPreviewFormat(ImageFormat.YV12);

            Camera.Parameters parameters = mCamera.getParameters();
            List<Camera.Size> previewSizeList = parameters.getSupportedPreviewSizes();
            for (int i = 0; i < previewSizeList.size(); i++)
            {
                Camera.Size size = previewSizeList.get(i);

                Log.i("PREVIEW_SIZE", String.format("camera preview width=%d,height=%d",size.width,size.height));
            }

            //设置预览数据大小
            params.setPreviewSize(mWidth, mHeight);
            //设置图片大小
            //params.setPictureSize(mWidth, mHeight);

            //相机设置参数
            mCamera.setParameters(params);


            //这一步是最关键的，使用surfaceTexture来承载相机的预览，而不需要设置一个可见的view
            //设置预览
            mCamera.setPreviewTexture(surfaceTexture);
            //设置预览回调
            mCamera.setPreviewCallback(this);
            //开始预览
            mCamera.startPreview();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭相机
     */
    public void closeCamera() {
        Log.i(TAG, "closeCamera");
        try {
            if (null != mCamera) {
                //置空预览回调
                mCamera.setPreviewCallback(null);
                //停止预览
                mCamera.stopPreview();
                //释放
                mCamera.release();
                //置空
                mCamera = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }



    /**
     * 预览数据回调
     * @param data
     * @param camera
     */
    @Override
    public void onPreviewFrame(final byte[] data, Camera camera) {
        if (this.mCamera == null) {
            return;
        }


        //获取参数
        Camera.Parameters parameters = camera.getParameters();
        //长度
        final int width = parameters.getPreviewSize().width;
        //宽度
        final int height = parameters.getPreviewSize().height;

        //Log.e(TAG, "onPreviewFrame: width > " + width + " > height > " + height);

        //Log.e(TAG, "onPreviewFrame: thread > " + Thread.currentThread() );

        byte[] newData = rotateYUV420Degree270(data, width, height);
        /*try {
            if (videoEncode != null) {
                videoEncode.encode(newData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        JniUtil.sendFrameData(newData, height, width);

        //mediaRecordManager.encodeVideo(newData);

        mGlSurfaceView.requestRender();

    }

    /**
     * 旋转270度
     * @param data
     * @param imageWidth
     * @param imageHeight
     * @return
     */
    private byte[] rotateYUV420Degree270(byte[] data, int imageWidth, int imageHeight){
        byte[] yuv = new byte[imageWidth * imageHeight * 3/2];
        // Rotate the Y luma
        int i =0;
        for(int x = imageWidth-1;x >=0;x--){
            for(int y =0;y < imageHeight;y++){
                yuv[i]= data[y*imageWidth+x];
                i++;
            }
        }// Rotate the U and V color components
        i = imageWidth * imageHeight;

        int j = imageWidth * imageHeight * 5 / 4;

        for (int x = imageWidth / 2; x > 0; x--) {
            for (int y = 0; y < imageHeight / 2; y++) {
                yuv[j] = data[imageWidth * imageHeight + y * imageWidth / 2 +  x - 1  ];
                j++;
                yuv[i] = data[imageWidth * imageHeight * 5 / 4 + y * imageWidth / 2 + x - 1];
                i++;
            }
        }
        return yuv;
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        JniUtil.resize(width, height);
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        JniUtil.step();
    }

    public void destroy() {
        closeCamera();
    }





}
